package sz.szsmk.citizencard.ui.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chenenyu.router.annotation.Route;
import com.google.android.flexbox.FlexboxLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.QueryBalanceActivityBinding;
import sz.szsmk.citizencard.db.BalanceDao;
import sz.szsmk.citizencard.db.BalanceDaoDao;
import sz.szsmk.citizencard.dialog.TwoButtonDialog;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.Book;
import sz.szsmk.citizencard.model.network.bean.request.QueryBalanceRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryUserBindCardRes;
import sz.szsmk.citizencard.mvp.contract.IQueryBalanceContact;
import sz.szsmk.citizencard.mvp.presenter.QueryBalancePresenter;
import sz.szsmk.citizencard.ui.adapter.BalancePopRvAdapter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.util.StringUtils;
import sz.szsmk.citizencard.util.Util;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/7/13 19:37
 * description:
 */
@Route("querybalance")
public class QueryBalanceActivity extends IBaseActivity<QueryBalancePresenter, QueryBalanceActivityBinding>
        implements IQueryBalanceContact.IQueryBalanceView, View.OnClickListener {

    private Dialog dialog;
    //    private ArrayList<String> cardList = new ArrayList<>();
//    private JSONArray jsonArray;
    private ArrayList<String> list;
    private String etCard;

    private LinearLayout layout;
    private PopupWindow popupWindow;
    private int type = 0;
    private BalancePopRvAdapter popRvAdapter;
    private RecyclerView popRv;
    ArrayList<String> bindCard = new ArrayList<>();
    private BalanceDaoDao balanceDaoDao;
    private List mList;
    private List<BalanceDao> balanceDaos;
    private FlexboxLayout flexboxLayout;
    private boolean isAcard;

    @Override
    protected int attachLayoutRes() {
        return R.layout.query_balance_activity;
    }

    @Override
    protected void initInjector() {

        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {
        layout = (LinearLayout) getLayoutInflater().inflate(R.layout.pup_balance, null, false);
        popupWindow = new PopupWindow(layout, 550, 400);
        popRv = (RecyclerView) layout.findViewById(R.id.pop_rv);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        popRv.setLayoutManager(manager);
        popRvAdapter = new BalancePopRvAdapter(this);
        popRv.setAdapter(popRvAdapter);

        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_bg_white));
        // 设置PopupWindow是否能响应外部点击事件
        popupWindow.setOutsideTouchable(true);
        // 设置PopupWindow是否能响应点击事件
        popupWindow.setTouchable(true);
        balanceDaoDao = DaggerApplication.getmDaoSession().getBalanceDaoDao();
        dataBinding.titleLayout.settingTitle.setText("余额查询");
        dataBinding.titleLayout.back.setOnClickListener(this);
        dataBinding.queryBtn.setOnClickListener(this);
        dataBinding.balanceDelall.setOnClickListener(this);
        dataBinding.balanceArrow.setOnClickListener(this);
        this.list = (ArrayList<String>) ACache.get(DaggerApplication.getIns()).getAsObject("balancecardList");
        flexboxLayout = dataBinding.flexboxLayout;
    }

    private TextView createNewFlexItemTextView(final Book book) {
        final TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER);
        textView.setText(book.getName());
        textView.setTextSize(12);
        textView.setTextColor(getResources().getColor(R.color.color_99a3a8));
        textView.setBackgroundResource(R.drawable.search_history_bg);

        textView.setTag(book.getName());
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e(Constant.TAG, book.getName());
            }
        });
        int padding = Util.dpToPixel(this, 4);
        int paddingLeftAndRight = Util.dpToPixel(this, 8);
        ViewCompat.setPaddingRelative(textView, paddingLeftAndRight, padding, paddingLeftAndRight, padding);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        int margin = Util.dpToPixel(this, 6);
        int marginTop = Util.dpToPixel(this, 16);
        layoutParams.setMargins(margin, marginTop, margin, 0);
        textView.setLayoutParams(layoutParams);
        textView.setOnTouchListener(new View.OnTouchListener() {

            private String mCard;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    Log.i("zhong", "onTouch: motionEventX : " + motionEvent.getX() + " viewWidth :" + view.getWidth());
                    if (motionEvent.getX() < view.getWidth() - view.getHeight() * 0.6) {
                        mCard = textView.getText().toString();
                        dataBinding.balanceEt.setText(mCard);
                    } else {
                        String cardId = (String) view.getTag();
                        for (BalanceDao dao : balanceDaos) {
                            if (dao.getCardNo().equals(cardId)) {
                                balanceDaoDao.delete(dao);
                                break;
                            }
                        }
                        reFreshData();
                    }
                }
                return false;
            }
        });
        return textView;
    }

    private void showDelDialog() {
        final TwoButtonDialog dialog = new TwoButtonDialog(this, "确认删除历史记录吗");
        dialog.setOnOkClickListener(new TwoButtonDialog.OnOkClickListener() {
            @Override
            public void onOkClick() {

                dialog.cancel();
            }
        });
        dialog.setOnCancelClickListener(new TwoButtonDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
                balanceDaoDao.deleteAll();
                dialog.cancel();
                reFreshData();
            }
        });
        dialog.show();
    }


    public void reFreshData() {
        balanceDaos = balanceDaoDao.loadAll();
        if (balanceDaos != null) {
            flexboxLayout.removeAllViews();
            for (int i = 0; i < this.balanceDaos.size(); i++) {
                String cardNo = balanceDaos.get(i).getCardNo() + "";
                L.e(Constant.TAG, "数据库查询：" + cardNo);
                Book model = new Book();
                model.setName(cardNo);
                flexboxLayout.addView(createNewFlexItemTextView(model));
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.queryBindCard();
        reFreshData();
    }

    @Override
    protected void updateViews() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void showAcardDialog(int balance, final String last_setle) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_query, null);
        builder.setView(dialogView);
        final TextView dialogBtn = (TextView) dialogView.findViewById(R.id.query_dialog_btn);
        TextView rechange = (TextView) dialogView.findViewById(R.id.query_dialog_rech);
        TextView mCard = (TextView) dialogView.findViewById(R.id.query_card_id);
        TextView mBalance = (TextView) dialogView.findViewById(R.id.query_dialog_balance);
        mCard.setText(last_setle);

        int i = balance;
        String formatPrice = StringUtils.decimalFormatPrice(i);
        if (i == 100000) {
            mBalance.setText("--" + "元");
        } else {
            mBalance.setText(formatPrice + "元");
        }
        final AlertDialog dialog = builder.create();
        dialogBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
        rechange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String access_token = ACache.get(QueryBalanceActivity.this).getAsString("access_token");
                Bundle bundle = new Bundle();
                bundle.putString("url", Constant.BASE_URL + "app-front-end/#/charge/main?cardNo=" + last_setle + "&access_token=" + access_token);
                JumpUtils.jumptoNatvie(QueryBalanceActivity.this, "webView", 0, bundle);
                dialog.cancel();
            }
        });
        dialog.show();
    }

    public static Boolean isNumber(String str) {
        for (int i = 0; i < str.length(); i++) {
            System.out.println(str.charAt(i));
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onClick(final View v) {
        int id = v.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.query_btn) {
            etCard = dataBinding.balanceEt.getText().toString();
            if (TextUtils.isEmpty(etCard)) {
                PubUtils.popTipOrWarn(this, "请输入您的卡号");
                return;
            }

            String start = etCard.substring(0, 1);
            String end = etCard.substring(etCard.length() - 1, etCard.length());
            String substring = etCard.substring(1, etCard.length() - 1);
            String num = etCard.substring(1, etCard.length());

            if (start.equals("A") || start.equals("a")) {
                if (end.equals("X") && isNumeric(substring) && etCard.length() == 9) {
                    isAcard = true;
                }
                if (end.equals("x") && isNumeric(substring) && etCard.length() == 9) {
                    isAcard = true;
                }
            }


            if (start.equals("A") || start.equals("a")) {
                if (isNumeric(num) && etCard.length() == 9) {
                    isAcard = true;
                } else {
                    isAcard = false;
                }
            } else {
                isAcard = false;
            }


            Pattern patternBcard = Pattern.compile("^2150[0-9]{12}$");
            boolean isBcard = patternBcard.matcher(etCard).matches();
            Boolean isShengCard;
            Boolean number = isNumber(etCard);
            if (etCard.length() == 19 && number) {
                isShengCard = true;
            } else {
                isShengCard = false;
            }
            isAcard = true;
            if (isAcard || isBcard || isShengCard) {

                int i = 0;
                for (i = 0; i < balanceDaos.size(); i++) {
                    String cardNo = balanceDaos.get(i).getCardNo();
                    if (cardNo.equals(etCard)) {
                        break;
                    }
                }

                if (i == balanceDaos.size()) {
                    BalanceDao balanceDao1 = new BalanceDao(etCard, null);
                    balanceDaoDao.insert(balanceDao1);
                }
                reFreshData();
                mPresenter.querybalance(etCard);
            } else {
                PubUtils.popTipOrWarn(this, "请输入一个正确的卡号");
                return;
            }
        } else if (id == R.id.balance_arrow) {
            final int width = Util.dpToPixel(QueryBalanceActivity.this, 160);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    setBackgroundAlpha(1.0f);
                }
            });
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    popupWindow.showAsDropDown(v, -width, 0);
                }
            });

            setBackgroundAlpha(0.5f);//设置屏幕透明度
            popRvAdapter.popItemOnclick(new BalancePopRvAdapter.PopItemInterface() {
                @Override
                public void onClick(View view, String cardNO) {
                    dataBinding.balanceEt.setText(cardNO);
                    popupWindow.dismiss();
//                        Toast.makeText(QueryBalanceActivity.this, "点击事件"+cardNO, Toast.LENGTH_SHORT).show();
                }
            });
        } else if (id == R.id.balance_delall) {
            showDelDialog();
        }
    }

    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }


    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }


    private void showMyDialog() {
        dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_query, null);
        dialog.setContentView(inflate);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setAttributes(lp);
        dialog.show();//显示对话框
    }

    @Override
    public void querybalanceError(QueryBalanceRes message) {
//        if (message.getCode().equals("P0004")) {
////            PubUtils.popTipOrWarn(this, message.getMessage());
//
//            showAcardDialog(100000, etCard);
//        } else {
            PubUtils.popTipOrWarn(this, message.getMessage());
//        }
    }

    @Override
    public void querybalanceSucc(QueryBalanceRes response, String etCard) {
        balanceDaos = balanceDaoDao.loadAll();
        L.e(Constant.TAG, "------------" + balanceDaos.size());
        int balance = response.getBalance();
        String last_setle = response.getLast_setle();
        showAcardDialog(balance, etCard);

    }

    @Override
    public void queryBindCardSucc(List<QueryUserBindCardRes.UserCardExBean> userCardEx) {
        popRvAdapter.setCardName(userCardEx);
        popRvAdapter.notifyDataSetChanged();
    }

    @Override
    public void queryBindCardFail(String string) {
    }
}
